<template>
  <j-modal
    switchFullscreen
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk" v-if="!disableSubmit">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="客户名称"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['custName',validatorRules.custName ]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="客户类型"
              >
              <cn-dict-select-tag
                triggerChange
                dictCode="cust_type"
                :disabled="disableSubmit"
                placeholder="请选择"
                :options="{value:'dictDataCode',label:'dictDataDesc'}"
                v-decorator.trim="['custType', validatorRules.custType]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="客户级别"
              >
              <cn-dict-select-tag
                triggerChange
                dictCode="cust_level"
                :disabled="disableSubmit"
                placeholder="请选择"
                :options="{value:'dictDataCode',label:'dictDataDesc'}"
                v-decorator.trim="['custLevel', validatorRules.custLevel]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="合作方式"
              >
              <cn-dict-select-tag
                triggerChange
                dictCode="cpt_manner"
                :disabled="disableSubmit"
                placeholder="请选择"
                :options="{value:'dictDataCode',label:'dictDataDesc'}"
                v-decorator.trim="['cooperationWayCode', validatorRules.cooperationWayCode]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="默认发货地编号"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['defaultDeliveryAddressCode', ]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="默认发货地"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['defaultDeliveryAddress', ]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="默认发货地2编号"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['defaultDeliveryAddress2Code', ]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="默认发货地2"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['defaultDeliveryAddress2', ]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="价格组"
              >
              <cn-dict-select-tag
                triggerChange
                dictCode="price_group"
                :disabled="disableSubmit"
                placeholder="请选择"
                :options="{value:'dictDataCode',label:'dictDataDesc'}"
                v-decorator.trim="['priceGroup', ]"/>
            </a-form-item>
          </a-col>
<!--          <a-col :md="12" :sm="24">-->
<!--            <a-form-item-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--              label="渠道"-->
<!--              >-->
<!--              <cn-dict-select-tag-->
<!--                triggerChange-->
<!--                dictCode="channel"-->
<!--                :disabled="disableSubmit"-->
<!--                placeholder="请选择"-->
<!--                :options="{value:'dictDataCode',label:'dictDataDesc'}"-->
<!--                v-decorator.trim="['channelCode', validatorRules.channelCode]"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="营业执照号"
            >
              <a-input v-decorator="['businessLicenseNum']" :disabled="disableSubmit" placeholder="请输入"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="所属组织"
            >
              <j-tree-select
                ref="selectRef"
                placeholder="选择组织"
                @change="handleDepartCode"
                v-decorator="['orgCode', validatorRules.orgCode]"
                data-type="org"
              />
            </a-form-item>
          </a-col>
          <!--          行政区域-->
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="所在行政区域"
            >
              <cn-area-linkage v-model="belongRegion"
                               type="cascader"
                               :province.sync="form.province"
                               :disabled="disableSubmit"
                               placeholder="请选择"
                               :city.sync="form.city"
                               :area.sync="form.area"
                               @change="handlePca"/>
            </a-form-item>
          </a-col>

          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系人"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['linkman', ]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系人电话"
            >
              <a-input v-decorator="['telephone', ]" :disabled="disableSubmit" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系地址"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['address', ]"/>
            </a-form-item>
          </a-col>

          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['remarks', ]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="营业执照">
              <j-image-upload class="avatar-uploader" text="上传"
                              v-decorator="[ 'businessLicense', {}]"></j-image-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <div style="display: flex;padding-left: 5.5%;border-top: 1px dashed #fefefe;padding-top:10px">
    </div>
  </j-modal>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import CnAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile, isPermit } from '@/utils/validate'
import UploadImage from '@/components/upload-image/UploadImage'
import JImageUpload from '@/components/cn-form/JImageUpload'
import Area from '@/components/utils/Area'
import JUpload from '@/components/cn-form/JUpload'
import { addUser, editUser, queryUserRole, queryall, queryDepartTreeList } from '@/api/api'

const generateUUID = function (withSeparator = true) {
  let d = new Date().getTime()
  d = (d + '').substring(5, (d + '').length)
  return d * 1
}
export default {
  name: 'dealer-modal',
  components: { JTreeSelect, CnAreaLinkage, UploadImage, JImageUpload, JUpload },
  data() {
    return {
      treeData:[],
      sendPro: false,
      ProductAdress: [],
      remarks: '',
      dataSurces2: [],
      formChoice: [],
      showCode: false,
      remembertext: '',
      dataSource: [],
      forms: {
        custName: '请选择',
        realName: '请选择',
        orgName: ''
      },
      dataSurces: [],
      // dataSurces3: [],
      manobjList: [0],
      belongRegion: '',
      // 财务表头
      financials: [{ id: generateUUID(false) }],
      certificatePhotos: [],
      areaData: '',
      areaLinkage: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      selectedRowKeys: [],
      selectedRowKeys1: [],
      selectionRows1: [],
      selectionRows: [],
      validatorRules: {
        telephone: {
          rules: [
            { required: true, message: '', trigger: 'submit' },
            {
              validator: function (rule, value, callback) {
                if (!isMobile(value)) {
                  callback(new Error(''))
                }
                callback()
              }
            }
          ]
        },
        businessLicense: {
          rules: [
            { required: true, message: '', trigger: 'submit' },
            {
              validator: function (rule, value, callback) {
                if (!isPermit(value)) {
                  callback(new Error(''))
                }
                callback()
              }
            }
          ]
        },
        custName: {
          rules: [
            { required: true, message: '请输入客户名称' }
          ]
        },
        warehouseName: {
          rules: [
            { required: true, message: '' }
          ]
        },
        address: {
          rules: [
            { required: true, message: '' }
          ]
        },
        linkman: {
          rules: [
            { required: true, message: '' }
          ]
        },
        telphone: {
          rules: [
            { required: true, message: '' }
          ]
        },
        dictDataCode: {
          rules: [
            { required: true, message: '' }
          ]
        },
        terminalType: {
          rules: [
            { required: true, message: '' }
          ]
        },
        terminalLevel: {
          rules: [
            { required: true, message: '' }
          ]
        },
        store: {
          rules: [
            { required: true, message: '' }
          ]
        },
        orgCode: {
          rules: [
            { required: true, message: '' }
          ]
        }
      },
      addOrUpdateUrl: window._CONFIG['domianURL'] + '/customerController/saveOrUpdateEntity'
    }
  },

  created() {
    this.initAreaData()
    console.log(this.areaData);
  },
  methods: {

    // loadTree() {
    //   var that = this
    //   queryDepartTreeList({ permflag: 'user_page_impl_add_org' }).then((res) => {
    //     if (res.success) {
    //       that.treeData = []
    //       let treeList = res.result
    //       for (let a = 0; a < treeList.length; a++) {
    //         let temp = treeList[a]
    //         temp.isLeaf = temp.leaf
    //         that.treeData.push(temp)
    //       }
    //     }
    //   })
    // },
    //添加请求参数，组织改变时，改变请求参数
    handleDepartCode(value, name) {
      console.log(name)
      this.model.departCode = ''
      this.model.departName = name
    },
    moment,
    handleDeleteRow(index) {
      if (index == 1) {
        this.selectedRowKeys.forEach(id => {
          let index = this.financials.findIndex(item => item.id == id)
          if (index != -1) {
            this.financials.splice(index, 1)
          }
        })
        this.selectedRowKeys = []
        this.selectionRows = []
        return
      }
      if (index == 2) {
        this.selectedRowKeys1.forEach(id => {
          let index = this.certificatePhotos.findIndex(item => item.id == id)
          if (index != -1) {
            this.certificatePhotos.splice(index, 1)
          }
        })
        this.selectedRowKeys1 = []
        this.selectionRows1 = []

      }
    },
    handleFile(list, fileList, index) {
      console.log(list, fileList)
      let data = {
        fileName: fileList[0].name,
        fileUrl: fileList[0].url,
        fileTypeName: fileList[0].type,
        fileSize: fileList[0].size,
        fileSuffix: fileList[0].name.split('.')[1],
      }
      this.$set(this.certificatePhotos[index], 'fileEntity', data)

    },
    onMomentChange(date, index) {
      this.$set(this.certificatePhotos[index], 'startTime', `${date[0]} 00:00:00`)
      this.$set(this.certificatePhotos[index], 'endTime', `${date[1]} 23:59:59`)
    },
    handlePca(code,e) {
      this.model.provinceCode = e[0]
      this.model.cityCode = e[1]
      this.model.areaCode = e[2]
      this.model.province = this.areaData.getText(code).split('/')[0]
      this.model.city = this.areaData.getText(code).split('/')[1]
      this.model.area = this.areaData.getText(code).split('/')[2]
    },
    randomHexColor() { //随机生成十六进制颜色
      var hex = Math.floor(Math.random() * 16777216).toString(16) //生成ffffff以内16进制数
      while (hex.length < 6) { //while循环判断hex位数，少于6位前面加0凑够6位
        hex = '0' + hex
      }
      return '#' + hex //返回‘#'开头16进制颜色
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      console.log(this.form)
      this.visible = true
      let pca = this.model.province + '/' + this.model.city + '/' + this.model.area
      this.belongRegion = this.areaData.getAreaCodeByText(pca) || ''
      this.financials = record.financials
      this.certificatePhotos = record.certificatePhotos
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
          //时间格式化
        }, 200)
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.financials = [{ id: generateUUID(false) }]
      this.certificatePhotos = []
    },

    onSelectChange1(selectedRowKeys, selectionRows) {
      this.selectedRowKeys1 = selectedRowKeys
      this.selectionRows1 = selectionRows
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },

    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let method = ''
          if (!this.model.id) {
            method = 'post'
          } else {
            method = 'post'
          }
          let formData = Object.assign(this.model, values, {
            financials: this.financials,
            certificatePhotos: this.certificatePhotos,
          })
          let reg = /^1[3-9]\d{9}$/
          if (!reg.test(formData.telephone)) {
            this.$message.info('请输入正确的手机号')
            this.isDisable = false
            this.confirmLoading = false
            return
          }
          console.log(formData)
          formData.departCode = formData.orgCode
          if (this.model.province) {
            formData.belongRegion = `${this.model.province}/${this.model.city}/${this.model.area}`
          }
          httpAction(this.addOrUpdateUrl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
            console.log(this.forms)
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },

    handleCancel() {
      this.close()
    },
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()
      }
    },

    // 新增行
    handleAddRow(name) {
      console.log(this[name])
      this[name].push({ id: generateUUID(false) })
    }

  }
}
</script>

<style scoped>
.gonghuoxinxi {
  width: 100%;
  border-bottom: 1px dashed black;
  margin: 10px 0;
  padding: 15px 5px;
  display: flex;
  flex-direction: column;
}
</style>
